#import "Settings.h"

@interface Settings()
@property (nonatomic, strong) NSUserDefaults* defaults;
@property (nonatomic, strong) NSMutableArray* listeners;
@property (nonatomic, strong) NSString* username;
@property (nonatomic, strong) NSString* password;
@property (nonatomic, strong) NSString* url;
@end

@implementation Settings

@synthesize defaults = _defaults;
@synthesize username = _username;
@synthesize password = _password;
@synthesize url = _url;
@synthesize listeners = _listeners;

-(NSMutableArray*)listeners {
    if (!_listeners) {
        _listeners = [NSMutableArray array];
    }
    return _listeners;
}

-(NSUserDefaults*)defaults {
    if (!_defaults) {
        _defaults = [NSUserDefaults standardUserDefaults];
    }
    return _defaults;
}

-(NSString*)username {
    if (!_username) {
        _username = [self.defaults stringForKey:@"username"];
        if (!_username) {
            _username = @"";
        }
    }
    return _username;
}

-(NSString*)password {
    if (!_password) {
        _password = [self.defaults objectForKey:@"password"];
        if (!_password) {
            _password = @"";
        }
    }
    return _password;
}

-(NSString*)url {
    if (!_url) {
        _url = [self.defaults objectForKey:@"url"];
        if (!_url) {
            _url = @"http://controlerepresentante.com.br";
        }
    }
    return _url;
}

-(void)subscribeToChanges:(id<SettingsListener>)listener {
    [self.listeners addObject:listener];
}

-(BOOL)setUsername:(NSString *)username password:(NSString *)password url:(NSString *)url error:(NSError**)error {
    self.username = username;
    self.password = password;
    self.url = url;
    [self.defaults setObject:username forKey:@"username"];
    [self.defaults setObject:password forKey:@"password"];
    [self.defaults setObject:url forKey:@"url"];
    [self.defaults synchronize];
    
    for (id<SettingsListener> listener in self.listeners) {
        BOOL result = [listener settingsChanged:self error:error];
        if (*error || !result) {
            return result;
        }
    }
    
    return YES;
}

@end
